package edu.itcs6112.za.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.itcs6112.za.domain.Contact;
import edu.itcs6112.za.domain.Order;
import edu.itcs6112.za.domain.OrderItem;
import edu.itcs6112.za.service.OrderService;
import edu.itcs6112.za.web.form.CustomerOrderModel;
import edu.itcs6112.za.web.form.OrderItemModel;
import edu.itcs6112.za.web.util.UrlUtil;

@RequestMapping("/orders")
@Controller
public class OrderController {
	final Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/getOrders", method = RequestMethod.GET,produces = "application/json")
	@ResponseBody
	public List<CustomerOrderModel> getOrders(@RequestParam("customerId") Long customerId){
		logger.debug("Fetching all orders for customer id" + customerId);
		List<Order> orders = orderService.findAllCustomerOrders(customerId);
		
		List<CustomerOrderModel> customerOrders = new ArrayList<CustomerOrderModel>();
		
		if(null != orders){
			for(Order ord : orders){
				CustomerOrderModel orderModel = new CustomerOrderModel();
				orderModel.setOrderAddress(ord.getOrderAddress());
				orderModel.setCustomerId(ord.getCustomerId());
				orderModel.setInvoiceNumber(ord.getInvoiceNumber());
				orderModel.setOrderDate(ord.getOrderDate());
				orderModel.setOrderId(ord.getOrderNumber());
				orderModel.setShipDate(ord.getShipDate());
				orderModel.setTotal(ord.getOrderTotal());
				orderModel.setTrackingNumber(ord.getTrackingNumber());
				orderModel.setStatus(ord.getStatus());
				orderModel.setShippingMethod(ord.getShippingMethod());
				if(null != ord.getItems()){
					for(OrderItem item : ord.getItems()){
						OrderItemModel itemModel = new OrderItemModel();
						itemModel.setDescription(item.getDescription());
						itemModel.setItemId(item.getItemId());
						itemModel.setPrice(item.getPrice());
						itemModel.setQuantity(item.getQuantity());
						
						orderModel.getOrderItems().add(itemModel);
					}
					customerOrders.add(orderModel);
				}
			}
		}
		return customerOrders;
	}
	
	
	
}
